import React, { useState, useEffect } from 'react';
import { obj_str, ErrView, uPlc, ck_empty, Input, uPrint, loc, MaTable, ge_date, cline, urlTb, BaseDlg, NuiBt } from 'sui';
import { put_log } from 'base/ctl/log';
import { g_line, g_wsn } from 'db/state';
import { get_gun, clear_gun } from 'base/api';

const DlgPrint = ({ open, setOpen, mt }) => {
    const [main, setMain] = useState();

    useEffect(() => {
        if (!open) {
            return;
        }

        urlTb(null, "get",
            {
                n: "printlog",
                obj: "*",
                opt: {
                    desc: true,
                    and: [
                        {eq: "line", v: cline()},
                        {gt: "time", v: ge_date(0)},
                    ]
                }
            },
            r => {
                let tmp = r["printlog"]["data"];

                tmp = tmp.filter(d => {
                    const qr = d.qr;
                    if (!qr) {
                        return false;
                    }

                    if (mt === "all") {
                        return true;
                    }

                    const ct = qr[0];

                    if (mt === "order") {
                        if (ct === "S" || ct === "C") {
                            return true;
                        }

                        return false;
                    }

                    if (ct !== mt) {
                        return false;
                    }

                    return true;
                });

                setMain(tmp);
            },
            e => setMain(null));
    }, [open, mt]);

    const hPrint = (d) => {
        uPrint(null, d, null, null, false);
        alert("打印信息已经发送")
    };

    const col = [
        {title: "批次号", field: 'sn', width: 100},
        {title: "型号", field: 'tech', width: 100},
        {title: "球径", field: 'ball', width: 100},
        {title: "二维码", field: 'qr', width: 100},
        {title: loc("client_23"), field: 'e_opt', width: 100, render: d => {
            return <NuiBt className="ml-8 h-16" color="green" hcmd={() => hPrint(d)}>打印</NuiBt>;
        }}
    ];

    return (
        <BaseDlg open={open} title="补打印" width="lg">
            <div style={{ height: "500px"}} className="flex flex-col">
                <MaTable col={col} row={main} page={8} paging={true} search={true}
                opt={{
                    minBodyHeight: 320,
                    maxBodyHeight: 320,
                }}/>
                <div className="inline-flex justify-end mt-3">
                    <NuiBt hcmd={() => setOpen(false)} className="mr-4 mb-3">取消</NuiBt>
                </div>
            </div>
        </BaseDlg>
    );
};

const DlgIn = ({ open, setOpen, hcmd, cur }) => {
    const [pos, setPos] = useState("");
    const [err, setErr] = useState("");
    const [st, setSt] = useState("");

    useEffect(() => {
        if (!open) {
            return;
        }

        setPos("");
        setErr("");
        setSt("");
    }, [open]);

    const hcode = (v) => {
        put_log("code", v, "扫码");

        const sp = v.split("#");
        const bsn = obj_str(cur, "bsn");

        if (sp[2] !== bsn) {
            setErr(`批次码不匹配: 正确为${bsn}, 扫码为: ${sp[2]}`);
            setSt(null);
        }

        setSt("ok");
        setErr("");
    };

    useEffect(() => {
        if (!open) {
            return;
        }

        const id = setInterval(() => {
            uPlc(null, "get",
                {
                    line: g_line(),
                    sn: g_wsn(),
                },
                r => {
                    const ret = get_gun(r);
                    if (!ret) {
                        return;
                    }

                    clear_gun();

                    hcode(ret);
                });
        }, 700);

        return () => clearInterval(id);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [open]);

    const hok = () => {
        const e = ck_empty(pos);
        if (e) {
            setErr("仓位不能为空");
            return;
        }

        if (st !== "ok") {
            setErr("编码验证失败");
            return;
        }

        setOpen(false);
        hcmd({ pos: pos });
    };

    const getSt = () => {
        if (st === "ok") {
            return <div className="bg-white text-2xl text-green-600 py-2 pl-4 mt-2">编码验证通过</div>;
        }

        return null;
    };

    return (
        <BaseDlg open={open} title="入库">
            <ErrView err="请用扫枪扫描物料二维码" tp="info"/>
            <Input label="仓位" value={pos} setValue={setPos} name="pos" className="mt-2 mb-3 ml-4"/>
            {getSt()}
            <div className="bg-white text-2xl text-red-600 py-2 pl-4 mt-2">{err}</div>
            <div className="inline-flex justify-end">
                <NuiBt hcmd={() => setOpen(false)} className="mr-4 mb-3">取消</NuiBt>
                <NuiBt hcmd={hok} className="mr-4 mb-3" color="green">确定</NuiBt>
            </div>
        </BaseDlg>
    );
};

const DlgSn = ({ open, setOpen, hcmd, old_data, new_data }) => {
    const hok = () => {
        setOpen(false);
        hcmd();
    };

    return (
        <BaseDlg open={open} title="注意">
            <ErrView err="此物料已存在，确定添加或忽略" tp="info"/>
            <div className="ml-4 mb-2">老仓位<span className="ml-4">{obj_str(old_data, "pos")}</span></div>
            <div className="ml-4 mb-2">新仓位<span className="ml-4">{obj_str(new_data, "pos")}</span></div>
            <div className="inline-flex justify-end">
                <NuiBt hcmd={() => setOpen(false)} className="mr-4 mb-3">忽略</NuiBt>
                <NuiBt hcmd={hok} className="mr-4 mb-3" color="green">添加物料</NuiBt>
            </div>
        </BaseDlg>
    );
};

export {DlgSn, DlgIn, DlgPrint};
